import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import Taro from '@tarojs/taro'
import { post } from '../utils/request'

/**
 * 用户信息接口
 */
export interface UserInfo {
  level_id: number;
  type_merchant: string | null;
  imaccid: string;
  card_balance: number;
  real_status: number;
  imtoken: string;
  recommend_pic: string | null;
  user_type: string | null;
  balance: number | null;
  avatar_url: string | null;
  name: string | null;
  blocked_balances: number | null;
  deposit: number | null;
  id: number;
  recommend_code: string | null;
  vip: number;
  merchantType: string | null;
}

/**
 * 用户 Store
 * 管理用户信息的状态和操作
 * 包含用户基本信息、VIP等级、余额、推广码等
 */
export const useUserStore = defineStore('user', () => {
  // 用户信息
  const userInfo = ref<UserInfo>({})

  // 用户token
  const token = ref<string>('')

  // 是否已登录
  const isLoggedIn = computed(() => !!token.value)

  // 是否为VIP用户
  const isVipUser = computed(() => userInfo.value.isVip && userInfo.value.vipLevel > 0)

  // 用户余额（格式化显示）
  const formattedBalance = computed(() => {
    return `¥${userInfo.value.balance.toFixed(2)}`
  })

  /**
   * 用户登录
   * @param loginData 登录数据
   */
  const login = async (loginData: { username: string; password: string }) => {
    try {
      // 这里应该调用实际的登录API
      // const response = await request.post('/api/login', loginData)
      
      // 模拟登录成功
      const mockUserInfo: UserInfo = {
        id: 1,
        username: loginData.username,
        avatar: 'http://www.dzgktf.com/templets/default/images/wtyt.jpg',
        vipLevel: 2,
        balance: 1580.50,
        promotionCode: 'ABC123456',
        phone: '138****8888',
        email: 'user@example.com',
        realName: '张三',
        isVip: true,
        vipExpireTime: '2024-12-31',
        registerTime: '2024-01-01',
        lastLoginTime: new Date().toISOString()
      }

      const mockToken = 'mock_token_' + Date.now()

      // 更新状态
      userInfo.value = mockUserInfo
      token.value = mockToken

      // 保存到本地存储
      Taro.setStorageSync('userInfo', mockUserInfo)
      Taro.setStorageSync('token', mockToken)

      return { success: true, message: '登录成功' }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: '登录失败' }
    }
  }

  /**
   * 用户登出
   */
  const logout = () => {
    // 清空状态
    userInfo.value = {
      username: '',
      avatar: '',
      vipLevel: 0,
      balance: 0,
      promotionCode: '',
      isVip: false
    }
    token.value = ''

    // 清除本地存储
    Taro.removeStorageSync('userInfo')
    Taro.removeStorageSync('token')

    // 跳转到登录页
    Taro.redirectTo({
      url: '/pages/webs/login'
    })
  }

  /**
   * 更新用户信息
   * @param newUserInfo 新的用户信息
   */
  const updateUserInfo = (newUserInfo: Partial<UserInfo>) => {
    userInfo.value = { ...userInfo.value, ...newUserInfo }
    
    // 更新本地存储
    Taro.setStorageSync('userInfo', userInfo.value)
  }

  /**
   * 更新用户余额
   * @param newBalance 新的余额
   */
  const updateBalance = (newBalance: number) => {
    userInfo.value.balance = newBalance
    Taro.setStorageSync('userInfo', userInfo.value)
  }

  /**
   * 更新VIP等级
   * @param newVipLevel 新的VIP等级
   */
  const updateVipLevel = (newVipLevel: number) => {
    userInfo.value.vipLevel = newVipLevel
    userInfo.value.isVip = newVipLevel > 0
    Taro.setStorageSync('userInfo', userInfo.value)
  }

  /**
   * 从本地存储恢复用户信息
   */
  const restoreUserInfo = () => {
    try {
      const storedUserInfo = Taro.getStorageSync('userInfo')
      const storedToken = Taro.getStorageSync('token')

      if (storedUserInfo && storedToken) {
        userInfo.value = storedUserInfo
        token.value = storedToken
      }
    } catch (error) {
      console.error('恢复用户信息失败:', error)
    }
  }

  /**
   * 检查用户是否已登录
   */
  const checkLoginStatus = () => {
    if (!token.value) {
      Taro.redirectTo({
        url: '/pages/webs/login'
      })
      return false
    }
    return true
  }

  /**
   * 获取用户推广链接
   */
  const getPromotionLink = computed(() => {
    return `https://nengliguangchang.suchi.hongyutiancheng.com/register?code=${userInfo.value.promotionCode}`
  })

  /**
   * 获取VIP等级显示文本
   */
  const getVipLevelText = computed(() => {
    const levelMap: Record<number, string> = {
      0: '普通用户',
      1: 'VIP会员',
      2: '黄金VIP',
      3: '钻石VIP',
      4: '至尊VIP'
    }
    return levelMap[userInfo.value.vipLevel] || '普通用户'
  })

  const fetchUserInfo = async () => {
    const res = await post('/my/index');
    console.log("res === info", res);
    if(res.code == 0){
      userInfo.value = res.data.columns
      console.log(userInfo.value)
    }
  }

  return {
    // 状态
    userInfo,
    token,
    isLoggedIn,
    isVipUser,
    formattedBalance,
    getPromotionLink,
    getVipLevelText,

    // 方法
    login,
    logout,
    updateUserInfo,
    updateBalance,
    updateVipLevel,
    restoreUserInfo,
    checkLoginStatus,
    fetchUserInfo
  }
}) 